package com.jh.user.business.impl;

import cn.jh.common.exception.ServiceException;
import com.jh.user.business.RealNameAuthPhotoBusiness;
import com.jh.user.business.UserLoginRegisterBusiness;
import com.jh.user.pojo.RealNameAuthPhoto;
import com.jh.user.pojo.User;
import com.jh.user.repository.RealNameAuthPhotoRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhugu
 * @version 1.0
 * 2018/12/17 16:36
 */
@Service
public class RealNameAuthPhotoBusinessImpl implements RealNameAuthPhotoBusiness {
    private static final Logger log = LoggerFactory.getLogger(RealNameAuthPhotoBusinessImpl.class);

    private static final String REAL_NAME_AUTH_PHOTO = "realNameAuthPhoto";

    @Value("${user.realname.uploadpath}")
    private String realnamePic;

    @Value("${user.realname.downloadpath}")
    private String downloadPath;

    private final RealNameAuthPhotoRepository realNameAuthPhotoRepository;
    private final UserLoginRegisterBusiness userLoginRegisterBusiness;

    public RealNameAuthPhotoBusinessImpl(RealNameAuthPhotoRepository realNameAuthPhotoRepository,
                                         UserLoginRegisterBusiness userLoginRegisterBusiness) {
        this.realNameAuthPhotoRepository = realNameAuthPhotoRepository;
        this.userLoginRegisterBusiness = userLoginRegisterBusiness;
    }

    @Override
    @Transactional
    public void uploadRealNameAuthPhoto(MultipartFile idCardPhoto, MultipartFile idCardBankPhoto, MultipartFile personPhoto, User user) throws ServiceException {
        try {
            RealNameAuthPhoto exist = realNameAuthPhotoRepository.findByUserId(user.getId());
            if (null == exist) {
                // 新增
                RealNameAuthPhoto realNameAuthPhoto = new RealNameAuthPhoto();
                uploadRealNamePhoto(idCardPhoto, idCardBankPhoto, personPhoto, realNameAuthPhoto, user);
                realNameAuthPhoto.setUserId(user.getId());
                realNameAuthPhoto.setBrandId(user.getBrandId());
                realNameAuthPhoto.setCreateTime(Calendar.getInstance().getTime());
                realNameAuthPhotoRepository.save(realNameAuthPhoto);

                user.setRealnameStatus("0");
                userLoginRegisterBusiness.saveUser(user);
            } else {
                // 更新
                uploadRealNamePhoto(idCardPhoto, idCardBankPhoto, personPhoto, exist, user);
                realNameAuthPhotoRepository.save(exist);

                user.setRealnameStatus("0");
                userLoginRegisterBusiness.saveUser(user);
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new ServiceException("上传失败，请稍后再试！");
        }
    }

    @Override
    public Map<String, String> findPhotoListByUserId(long userId) throws ServiceException {
        Map<String, String> map = new HashMap<>();
        RealNameAuthPhoto realNameAuthPhoto = realNameAuthPhotoRepository.findByUserId(userId);
        if (null == realNameAuthPhoto) {
            map.put("idCardPhoto", "");
            map.put("idCardBankPhoto", "");
            map.put("personPhoto", "");
            return map;
        }
        map.put("idCardPhoto", realNameAuthPhoto.getIdCardPhoto());
        map.put("idCardBankPhoto", realNameAuthPhoto.getIdCardBankPhoto());
        map.put("personPhoto", realNameAuthPhoto.getPersonPhoto());
        return map;
    }

    /**
     * 上传图片
     * @param idCardPhoto
     * @param idCardBankPhoto
     * @param personPhoto
     * @param realNameAuthPhoto
     */
    private void uploadRealNamePhoto(MultipartFile idCardPhoto, MultipartFile idCardBankPhoto, MultipartFile personPhoto, RealNameAuthPhoto realNameAuthPhoto, User user) {
        if (!idCardPhoto.isEmpty()) {
            String idCardPhotoPath = upload(idCardPhoto, "idCardPhoto", user);
            realNameAuthPhoto.setIdCardPhoto(idCardPhotoPath);
        }
        if (!idCardBankPhoto.isEmpty()) {
            String idCardBankPhotoPath = upload(idCardBankPhoto, "idCardBankPhoto", user);
            realNameAuthPhoto.setIdCardBankPhoto(idCardBankPhotoPath);
        }
        if (!personPhoto.isEmpty()) {
            String personPhotoPath = upload(personPhoto, "personPhoto", user);
            realNameAuthPhoto.setPersonPhoto(personPhotoPath);
        }
    }

    private String upload(MultipartFile multipartFile, String fileName, User user) {
        String uoloadPathStr = realnamePic + user.getId() + File.separator + REAL_NAME_AUTH_PHOTO + File.separator;

        // 创建目录
        File createFile = new File(uoloadPathStr);
        boolean mkdirs = createFile.mkdirs();
        if (!mkdirs) {
            log.warn("创建{}失败，请检查目录权限！", uoloadPathStr);
        }

        String originalFilename = fileName + "-" + user.getId() + ".png";
        File file = new File(uoloadPathStr + originalFilename);

        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return downloadPath + user.getId() + File.separator + REAL_NAME_AUTH_PHOTO + File.separator + originalFilename;
    }
}
